package com.LeeCode;

import java.util.HashMap;

/**
 * 和为K的子数组
 */

public class Code560 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        int k = 3;
        System.out.println(new Code560().subarraySum(nums, k));

    }

    public int subarraySum(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j < nums.length; j++) {
                sum += nums[j];
                if (sum == k) {
                    count++;
                }
            }
        }
        return count;
    }

    public int subarraySum1(int[] nums, int k) {

        HashMap<Integer, Integer> map = new HashMap<>();
        int count = 0, preSum = 0;
        map.put(0, 1);

        for (int i = 0; i < nums.length; i++) {
            preSum += nums[i];
            int target = preSum - k;
            count += map.getOrDefault(target, 0);
            map.merge(preSum, 1, Integer::sum);
        }
        return count;
    }
}
